package com.smit.dvbclient;

import java.util.ArrayList;
import java.util.List;

import android.R.integer;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.smit.dvb.ChannelInfo;
import com.smit.dvb.IAdapterSmitDVB;

/**
 * @ClassName: DVBClient
 * @Description: 跨进程绑定到DVBService，获取节目信息，选择相应的节目，进入到【融合电视】进行播放
 * @author: visual
 * @date: 2014-3-20 上午11:20:28
 */
public class DVBClient extends Activity implements Handler.Callback
{

    final static String TAG = "DVBClient";
    final static String TCL_START_SMIT_DVB_ACTION = "com.smit.dvb.TCL_START_SMIT_DVB";
    final static String SMIT_DVB_PLAY_ACTION = "com.smit.dvb.PLAY_ACTION";
    final static String PLAY_CHANNEL_INDEX = "PLAY_CHANNEL_INDEX";
    final int MSG_INIT_LIST = 100;
    Handler msgHandler = new Handler(this);
    /* TCL 保存节目信息的列表 */
    List<ChannelInfo> channelInfoList = new ArrayList<ChannelInfo>();

    /* 用来在界面上显示的ListView 控件已经数据 */
    ListView lvChannelListView;
    ArrayList<String> alChannelArrayList = new ArrayList<String>();
    ArrayAdapter<String> aaChannelListAdapter;
    TextView textView;
    /* Smit DVB 接口，服务的连接 */
    Intent serviceIntent;
    IAdapterSmitDVB mDvbService;

    ServiceConnection serviceConnection = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            mDvbService = (IAdapterSmitDVB) IAdapterSmitDVB.Stub.asInterface(service);
            Common.Logd(TAG, "onServiceConnected********");
            /* 初始化控件和参数 */
            msgHandler.sendEmptyMessageDelayed(MSG_INIT_LIST, 500);
        }

        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            Common.Logd(TAG, "onServiceDisconnected********");
            mDvbService = null;
        }
    };
    
    @Override
    public boolean handleMessage(Message msg)
    {
        switch (msg.what)
        {
            case MSG_INIT_LIST:
                initItems();
                break;

            default:
                break;
        }
        return false;
    }
    /********************************************
     * Activity 函数
     ********************************************/
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Common.Logd(TAG, "onCreate********");
        setContentView(R.layout.activity_dvb_client);
        
        lvChannelListView = (ListView) findViewById(R.id.lv_channel_list);
        textView = (TextView) findViewById(R.id.textView1);
        textView.setText("Product Model: " + android.os.Build.MODEL + "," 
                + android.os.Build.VERSION.SDK_INT + "," 
                + android.os.Build.VERSION.RELEASE); 
    }
    public static final String ACTION_SMIT_DVB_SERVICE = "ACTION_SMIT_DVB_SERVICE"; // 广播消息名
    public static final String DVB_SERVICE_ID = "ID";                               // 消息ID
    public static final String DVB_SERVICE_PARAM = "PARAM";                         // 消息参数

    public static final int START_DVB_OK = 1;         // DVB初始化OK，这里做的是USB参数的初始化
    public static final int START_DVB_FAIL = 2;       // DVB未初始化成功，没有找到设备或没权限
   
    private boolean bHasUnregistered = true;    // 用来标记broadcast是否已经unregistered
    private boolean bDVBServiceOk = false;       // 用来标记DVBService是否正常，如果正常再收到拔出消息才结束应用

    BroadcastReceiver dvbBroadcastReceiver = new BroadcastReceiver()
    {
        public void onReceive(Context context, Intent intent)
        {
            if(intent == null) return;
            
            String action = intent.getAction();
            
            if (ACTION_SMIT_DVB_SERVICE.equals(action))
            {
                Common.Logd(TAG, ACTION_SMIT_DVB_SERVICE);
                int id = intent.getIntExtra(DVB_SERVICE_ID, -1);
                Common.Logd(TAG, "DVB_SERVICE_ID=" + id);

                switch (id)
                {
                    case START_DVB_OK:
                        bDVBServiceOk = true;
                        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
                        initItems();
                        break;
                    case START_DVB_FAIL:
                        bDVBServiceOk = false;
                        if (bHasUnregistered == false)
                        {
                            unregisterReceiver(dvbBroadcastReceiver);
                            bHasUnregistered = true;
                        }
                        Common.Logv(TAG, "DVBService.START_DVB_FAIL!");
                        break;
                }
            }
        }
    };
    @Override
    protected void onResume()
    {
        Common.Logd(TAG, "onResume********");
        /* DVB 服务消息监听 */
        IntentFilter dvbFilter = new IntentFilter();
        dvbFilter.addAction(ACTION_SMIT_DVB_SERVICE);
        registerReceiver(dvbBroadcastReceiver, dvbFilter);
        bHasUnregistered = false;
        
        /* 绑定后台服务 */
        Intent intent=new Intent();
        intent.setAction("com.smit.dvb.TCL_ADAPTER_SMIT_DVB");
        //startService(intent);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
        super.onResume();
    }

    @Override
    protected void onStop()
    {
        Common.Logd(TAG, "onStop********");
        unbindService(serviceConnection);
        if (bHasUnregistered == false)               // 用户手动退出会报监听没有取消的错误 
        {
            bHasUnregistered = true;
            unregisterReceiver(dvbBroadcastReceiver);
        }
        super.onStop();
    }

    
    /*******************************************
     * 自定义功能函数
     *******************************************/
    private void initItems()
    {
        if(mDvbService == null)
        {
            Common.Loge(TAG, "mDvbService is null in initItems!");
            return;
        }
        /* 获取频道列表 */
        try
        {
            mDvbService.getChannelList(1, channelInfoList);
        }
        catch (RemoteException e)
        {
            Common.Loge(TAG, "mDvbService.getChannelList exception!");
        }
        if(channelInfoList != null && channelInfoList.size() > 0)
        {
            int i = 1;
            for(ChannelInfo channelInfo:channelInfoList)
            {
                alChannelArrayList.add(String.format("%03d\t", i)+channelInfo.getServiceName());
                i++;
            }
        }
        if(channelInfoList.size() == 0)
        {
            ChannelInfo channelInfo = new ChannelInfo();
            alChannelArrayList.add("001 中央一台");
            channelInfo.setChannelNumber((short) 1);
            try
            {
                mDvbService.channelSelect(channelInfo);
            }
            catch (RemoteException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        aaChannelListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, alChannelArrayList);
        if (lvChannelListView != null)
        {
            lvChannelListView.setAdapter(aaChannelListAdapter);
        }
        /* 设置ListView 按键监听，选择节目，进入【融合电视】播放 */
        lvChannelListView.setOnItemClickListener(new OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
            {
                if (id < channelInfoList.size())
                {
                    try
                    {
                         ChannelInfo channelInfo = channelInfoList.get((int) id);
                         channelInfo.setChannelNumber((short)0);
//                        ChannelInfo channelInfo = new ChannelInfo();
//                        channelInfo.setChannelNumber((short)1);
                        mDvbService.channelSelect(channelInfo);
                    }
                    catch (RemoteException e)
                    {
                        Common.Loge(TAG, "mDvbService.channelSelect exception!");
                    }
                }
            }
        });
    }

}
